import { request } from "../../request/index.js"
import regeneratorRuntime from '../../lib/runtime/runtime'

// pages/goods_detail/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    goodsObj: {}
  },
  // 商品对象
  GoodsInfo: {},
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const { goods_id } = options;
    this.getGoodSDetail(goods_id);
  },

  // 获取商品详情数据
  async getGoodSDetail(goods_id) {
    const res = await request({ url: "/goods/detail", data: { goods_id } });
    this.GoodsInfo = res.data.message;
    this.setData({
      goodsObj: {
        goods_name: res.data.message.goods_name,
        goods_price: res.data.message.goods_price,
        goods_introduce: res.data.message.goods_introduce.replace(/\.webp/g, '.jpg'),
        pics: res.data.message.pics
      }
    })
  },

  // 轮播图放大预览
  handlePrevewImage(e) {
    // 构造要预览的数组
    const urls = this.GoodsInfo.pics.map(v=>v.pics_mid);
    // 接受传递过来的url
    const current = e.currentTarget.dataset.url;
      wx.previewImage({
        current, // 当前显示图片的http链接
        urls// 需要预览的图片http链接列表
      })
  },

  // 加入购物车
  handleCartAdd(){
    // 获取缓存中的购物车 数组
    let cart = wx.getStorageSync("cart")||[];
    // 判断商品对象是否在购物车数组中
    let index = cart.findIndex(v=>v.goods_id===this.GoodsInfo.goods_id);
    if(index===-1){
      this.GoodsInfo.num=1;
      this.GoodsInfo.checked=true;
      cart.push(this.GoodsInfo);
    }else{
      cart[index].num++;
    }
    // 把购物车重新添加到缓存中
    wx.setStorageSync("cart", cart);
    // 弹窗提示
    wx.showToast({
      title: '添加成功',
      icon: 'success',
      mask: true
    });
  }
})